package org.hgvc.webapp.ets.jsf.beans.agent;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.swing.Spring;

import org.hgvc.webapp.ets.bo.Agent;
import org.hgvc.webapp.ets.bo.Agreement;
import org.hgvc.webapp.ets.bo.CommissionSchemaPaymentRange;
import org.hgvc.webapp.ets.spring.dao.AgentHbmDao;
import org.hgvc.webapp.ets.spring.dao.AgreementHbmDao;
import org.hgvc.webapp.ets.spring.dao.MemberHbmDao;
import org.hgvc.webapp.ets.spring.service.MemberService;
import org.jocsb.base.util.SpringUtils;

import com.j6.framework.util.DateUtil;
import com.j6.framework.util.J;
import com.j6.framework.util.StringUtil;

public class AdminCommissionBean {
	private boolean started =false; 
	private AgentHbmDao agentDao;
	private MemberService memberService;
	private MemberHbmDao memberDao;
	private AgreementHbmDao agreementDao;
	private int month;
	private int year;

	public AdminCommissionBean() {
		J.printPositif("AdminCommissionBeanAdminCommissionBean");
	};

	public int getMonth() {
		return month;
	}

	public void setMonth(int month) {
		this.month = month;
	}

	public int getYear() {
		return year;
	}

	public void setYear(int year) {
		this.year = year;
	}

	public List<String> getAffectQuotaYearMonth(Agent agent, int month , int year) throws Exception{
		//TODO no bother about agreement transfer agent
		
		List<String> monthYears = new ArrayList<String>();
		
//		select membershipchangeLog.agreement.date.month/year where membershipchangeLog .data = this month
		monthYears.addAll(memberDao.getMonthYearOfAgreementMembershipChange(agent.getAgentId(), month, year));
		
		monthYears.addAll(agreementDao.getAgreementsTerminateMonthYear(agent.getAgentId(), year, month));
		//agreement terminate affect quota
		
		//new Agreement
		monthYears.addAll(agreementDao.getNewAgreementMonthYear(agent.getAgentId(), year, month));
		return monthYears;
		 
	}

	public boolean isSchemeChange(CommissionSchemaPaymentRange range, String schemeId, double totalPrice, double commissionPercentage) throws Exception{
		
		if (commissionPercentage != range.getPercent().doubleValue()){
			return true;
		}
		return false;
	}

	public void calculateCommison(Agreement agreement){

	}
	public boolean isContainsString(List<String> allString, String str){
		for(String s : allString){
			if (s.equalsIgnoreCase(str)){
				return true;
			}
		}
		return false;
	}
	public boolean isRequireCountAllCommision(List<String> monthYears, int month, int year){
//		List<String> newAgre = agreementDao.getNewAgreementMonthYear(agent.getAgentId(), year, month);
//		if (newAgre!=null && newAgre.size()>0){
//			return true;
//		}
		
		// check not same commision in the given month, year
		double percentage = 0;
		for(String s : monthYears){
			if (Integer.parseInt(s.split(";")[0]) ==  month  &&
					Integer.parseInt(s.split(";")[1]) ==  year  ){
				percentage = Double.parseDouble(s.split(";")[2]);
			}
		} 
		for(String s : monthYears){
			if ( Integer.parseInt(s.split(";")[0]) ==  month  &&
					Integer.parseInt(s.split(";")[1]) ==  year  &&
					Double.parseDouble(s.split(";")[2] )!=percentage){
				
				return true;
			}
		}
		/////
		
		return false;
	}
	
	public AgentHbmDao getAgentDao() {
		return agentDao;
	}

	public void setAgentDao(AgentHbmDao agentDao) {
		J.printPositif("setAgentDaosetAgentDaosetAgentDaosetAgentDao"+agentDao);
		this.agentDao = agentDao;
	}

	public void setMemberService(MemberService memberService) {
		J.printPositif("setMemberServicesetMemberServicesetMemberServicesetMemberService");
		this.memberService = memberService;
	}

	public void setMemberDao(MemberHbmDao memberDao) {
		this.memberDao = memberDao;
	}

	public void setAgreementDao(AgreementHbmDao agreementDao) {
		this.agreementDao = agreementDao;
	}

	public void run() throws Exception{
		
		Calendar c = Calendar.getInstance();
		c.add(Calendar.DAY_OF_MONTH, -1);
		Date d = c.getTime();
		month =DateUtil.setTime(d).get(Calendar.MONTH);
		month++;
		year =DateUtil.setTime(d).get(Calendar.YEAR);
		
	//	if (!started){
			//TODO no bother about agreement transfer agent
			//TODO now just cater for agent.scheme.type=AGENT_COMM_SCH_COMM_TYPE_RANGE
			try{
			List<Agent> agents = agentDao.getAgentForCommission();
			for(Agent agent : agents){
				System.out.println("Start Commission Processing agent "+agent.getAgentRegNo()+"...");	
				
				List<String> monthYears = getAffectQuotaYearMonth(agent, month , year);
				List<String> monthYearsProcessed = new ArrayList<String>();
				for(String monthYear : monthYears){
					if (!isContainsString(monthYearsProcessed,monthYear.split(";")[0]+""+monthYear.split(";")[1])){
						int affectMonth = new Integer( monthYear.split(";")[0]);
						int affectYear= new Integer( monthYear.split(";")[1]);
						//double commissionPercentage= new Integer( monthYear.split(";")[2]);
						double totalSale = agreementDao.getTotalAgreementPrice(agent.getAgentId(), affectYear, affectMonth);
						CommissionSchemaPaymentRange range= agentDao.getCommissionSchemaPaymentRangeBySchId(agent.getSchema().getCommSchId(),totalSale, affectYear, affectMonth);
						//is all same scheme % for active agreement
						//is scheme change? for active agreement.
//						if (isSchemeChange(range,agent.getSchema().getCommSchId(), totalSale,commissionPercentage)
//								|| isRequireCountAllCommision(monthYears, affectMonth,affectYear )){
							List<Agreement>agreements= agreementDao.getAgreementForCommission(agent.getAgentId(),affectMonth,affectYear);
							 
							memberService.updateAgreementNewCommission(agreements,range, month ,year);
							 
//						}else{
//							
//						}
						monthYearsProcessed.add(monthYear.split(";")[0]+""+monthYear.split(";")[1]);
					}
				}
				
				memberService.saveAgentCommission(agent , month, year);
				
				System.out.println("End Commission Processing agent "+agent.getAgentRegNo());	
				
			}
			}catch(Exception e){
				e.printStackTrace();
			}
	//		started = true;
	//	}
	}
	
}
